package com.juguo.charginganimation;

import androidx.annotation.NonNull;
import androidx.databinding.DataBindingUtil;
import androidx.viewpager.widget.ViewPager;

import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;

import com.fenghuajueli.lib_ad.AdShowUtils;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.juguo.charginganimation.Adapter.FragmentAdapter;
import com.juguo.charginganimation.Base.Baseactivty;
import com.juguo.charginganimation.Data.remote.RetrofitManager;
import com.juguo.charginganimation.View.gallery.GallerDetailMake;
import com.juguo.charginganimation.View.gallery.GalleryDetailScYyds;
import com.juguo.charginganimation.View.gallery.GalleryDetailYyds;
import com.juguo.charginganimation.databinding.ActivityMainBinding;
import com.juguo.charginganimation.repository.PixabayService;
import com.juguo.charginganimation.utils.RxUtils;
import com.juguo.charginganimation.utils.ToastUtil;

import java.io.File;

import io.reactivex.disposables.CompositeDisposable;


public class MainActivity extends Baseactivty {

    protected String TAG = "MainActivity";
    private ActivityMainBinding binding;
    private BottomNavigationView navigation;
    private ViewPager mViewPager;
    //是否是第一次使用
    private boolean isFirstUse;
    private MediaPlayer mediaPlayer = new MediaPlayer();
    private final static String USB_ACTION = "android.hardware.usb.action.USB_STATE";
    private CompositeDisposable mDisposable = new CompositeDisposable();

    //插屏广告
    private long startTime = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
        initViewAndData(); //广告有误类型
        initView();
        //注册家广播
        IntentFilter filter = new IntentFilter();
        filter.addAction(Intent.ACTION_BATTERY_CHANGED);
        filter.addAction(Intent.ACTION_BATTERY_LOW);
        filter.addAction(Intent.ACTION_BATTERY_OKAY);
        filter.addAction(Intent.ACTION_POWER_CONNECTED);
        filter.addAction(Intent.ACTION_POWER_DISCONNECTED);
        filter.addAction(USB_ACTION);
        registerReceiver(mBroadcastReceiver, filter);
        registerReceiver(mBroadcastReceiver, new IntentFilter(USB_ACTION));
        if (MainApplication.getsInstance().isShowAd) {
            AdShowUtils.getInstance().loadInteractionAd(this,"main_chaping_ad");
        }
    }

    /**
     * 电量检测
     */
    private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            boolean isBatteryCharging = false;
            String action = intent.getAction();
            switch (action) {
                case USB_ACTION:
                    boolean connected = intent.getExtras().getBoolean("connected");
                    if (connected) {
//                        ToastUtil.showToast(MainActivity.this, "USB连接");
                    } else {
//                        ToastUtil.showToast(MainActivity.this, "USB未连接");
                        mediaPlayer.pause();
                    }
                    break;

                case Intent.ACTION_BATTERY_LOW:
//                    ToastUtil.showToast(MainActivity.this, "电量过低,");
                    break;

                case Intent.ACTION_BATTERY_OKAY:
//                    ToastUtil.showToast(MainActivity.this, "电量满,");
                    break;

                case Intent.ACTION_POWER_CONNECTED:
                    ToastUtil.showToast(MainActivity.this, "电源已接通");
                    File file = new File("/data/data/" + MainApplication.getsInstance().getPackageName().toString() + "/shared_prefs", "ImageYyds.xml");
                    if (file.exists()) {
                        Intent intentYyds = new Intent(MainActivity.this, GalleryDetailYyds.class);
                        intentYyds.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);  //只启动一个实例
                        startActivity(intentYyds);
                    }
                    File fileSc = new File("/data/data/" + MainApplication.getsInstance().getPackageName().toString() + "/shared_prefs", "ImageYydsSc.xml");
                    if (fileSc.exists()) {
                        Intent intentYyds = new Intent(MainActivity.this, GalleryDetailScYyds.class);
                        intentYyds.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);  //只启动一个实例
                        startActivity(intentYyds);
                    }
                    File fileZzdh = new File("/data/data/" + MainApplication.getsInstance().getPackageName().toString() + "/shared_prefs", "ImageZzdh.xml");
                    if (fileZzdh.exists()) {
                        Intent intentZzdh = new Intent(MainActivity.this, GallerDetailMake.class);
                        intentZzdh.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);  //只启动一个实例
                        startActivity(intentZzdh);
                    }
                    startBo();
                    break;

            }
        }
    };

    /**
     * 播放
     */
    private void startBo() {
        SharedPreferences sp = MainApplication.getsInstance().getSharedPreferences("chongdian", Context.MODE_PRIVATE);
        String chong_dian = sp.getString("chong_dian", "");
        try {
            mediaPlayer.setDataSource(chong_dian);//指定音频文件路径
            mediaPlayer.setLooping(false);//设置为循环播放
            mediaPlayer.prepare();//初始化播放器MediaPlayer
        } catch (Exception e) {
            e.printStackTrace();
        }
        //如果没在播放中，立刻开始播放。
        if (!mediaPlayer.isPlaying()) {
            mediaPlayer.start();
        }
        //播放完成监听
        mediaPlayer.setOnCompletionListener(mp -> {
            mediaPlayer.pause();
        });
    }


    public void initView() {
        // BottomNavigationView
        navigation = findViewById(R.id.nav_view);
        // 去除背景底色
        navigation.setItemIconTintList(null);
        // 实例化adapter，得到fragment
        FragmentAdapter fragmentAdapter = new FragmentAdapter(getSupportFragmentManager());
        mViewPager = findViewById(R.id.viewpager);
        // 建立连接
        mViewPager.setAdapter(fragmentAdapter);
        setNavigation();
    }

    /**
     * 设置底部导航栏
     */
    public void setNavigation() {
        // 底部导航栏点击事件
        navigation.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                resetIcon();
                switchMenu(item);
                return true;
            }
        });
        //viewpager监听事件，当viewpager滑动时得到对应的fragment碎片
        mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {

            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                resetIcon();
                navigation.getMenu().getItem(position).setChecked(true);
                switchMenu(navigation.getMenu().getItem(position));
            }

            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });
    }

    /**
     * 导航栏切换方法
     */
    private void switchMenu(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.AnimationFragment:
                item.setIcon(R.mipmap.cddh);
                mViewPager.setCurrentItem(0);
                break;
            case R.id.PromptFragment:
                item.setIcon(R.mipmap.cdts);
                mViewPager.setCurrentItem(1);
                break;
            case R.id.MakeFragment:
                item.setIcon(R.mipmap.cdzz);
                mViewPager.setCurrentItem(2);
                break;
            case R.id.PersonalCenterFragment:
                item.setIcon(R.mipmap.grzx);
                mViewPager.setCurrentItem(3);
                break;
            default:
        }
    }

    /**
     * 重置底部导航栏图标
     */
    private void resetIcon() {
        MenuItem home = navigation.getMenu().findItem(R.id.AnimationFragment);
        home.setIcon(R.mipmap.cddh_mb);
        home = navigation.getMenu().findItem(R.id.PromptFragment);
        home.setIcon(R.mipmap.cdts_mb);
        home = navigation.getMenu().findItem(R.id.MakeFragment);
        home.setIcon(R.mipmap.cdzz_mb);
        home = navigation.getMenu().findItem(R.id.PersonalCenterFragment);
        home.setIcon(R.mipmap.grzx_mb);
    }



    /**
     * 读写权限为危险权限，在Manifest中注册后，还需要动态获取权限
     */
    public void checkPermission() {
        boolean isGranted = true;
        if (android.os.Build.VERSION.SDK_INT >= 23) {
            if (this.checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                isGranted = false;
            }
            if (this.checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                isGranted = false;
            }
            Log.i("读写权限获取", " ： " + isGranted);
            if (!isGranted) {
                this.requestPermissions(
                        new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission
                                .ACCESS_FINE_LOCATION,
                                Manifest.permission.READ_EXTERNAL_STORAGE,
                                Manifest.permission.WRITE_EXTERNAL_STORAGE},
                        102);
            }
        }

    }

    /**
     * 穿山甲
     */
    private void initViewAndData() {
        PixabayService service = RetrofitManager.getInstance()
                .getRetrofit()
                .create(PixabayService.class);
        mDisposable.add(service.getAppIdAdvertise("wx9ooOL2SleR78Slil")
                .compose(RxUtils.schedulersTransformer())
                .subscribe(privacyBean -> {
                    Log.d(TAG, "accept: " + privacyBean);
                    String startAdFlag = privacyBean.getResult().getStartAdFlag();
                    //NONE 无  CSJ 穿山甲  SYS 自系统
                    if ("NONE".contains(startAdFlag)) {

                    } else if ("CSJ".equals(startAdFlag)) {

                    } else if ("SYS".equals(startAdFlag)) {
                    }
                }, throwable -> Log.d(TAG, "loadMore: " + throwable)));

    }




    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mBroadcastReceiver);
        AdShowUtils.getInstance().destroyInteractionAd("main_chaping_ad");
    }

    protected void onStop() {
        super.onStop();
    };

    @Override
    protected void onPause() {
        super.onPause();
    }
    @Override
    public void onBackPressed() {
        //方式一：将此任务转向后台
        moveTaskToBack(false);
        //方式二：返回手机的主屏幕
    /*Intent intent = new Intent(Intent.ACTION_MAIN);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    intent.addCategory(Intent.CATEGORY_HOME);
    startActivity(intent);*/
    }
}